﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using mjRegister.Entity;
using System.Threading;
using mjRegister.BAL;
using System.Collections;
using System.IO;

namespace mjRegister
{
    public partial class MyTeam : Form
    {
        private Form2 _ownerForm;
        private AccountInfo _accountInfo;

        IList<Thread> lstThread = new List<Thread>();

        User _user = new User();
        private ListViewColumnSorter lvwColumnSorter;

        bool is_oil_flag = true;
        bool is_can_oil_flag = true;

        Hashtable htFriend = new Hashtable();

        MyCarTeamInfo myCarTeamInfo = null;

        string verify = string.Empty;

        public MyTeam(Form2 ownerForm, AccountInfo accountInfo)
        {
            InitializeComponent();

            _ownerForm = ownerForm;
            _accountInfo = accountInfo;

            lvwColumnSorter = new ListViewColumnSorter(2);
            this.listView1.ListViewItemSorter = lvwColumnSorter;


        }

        private void listView1_ColumnClick(object sender, ColumnClickEventArgs e)
        {
            // 检查点击的列是不是现在的排序列.
            if (e.Column == lvwColumnSorter.SortColumn)
            {
                // 重新设置此列的排序方法.
                if (lvwColumnSorter.Order == SortOrder.Ascending)
                {
                    lvwColumnSorter.Order = SortOrder.Descending;
                }
                else
                {
                    lvwColumnSorter.Order = SortOrder.Ascending;
                }
            }
            else
            {
                // 设置排序列，默认为正向排序
                lvwColumnSorter.SortColumn = e.Column;
                lvwColumnSorter.Order = SortOrder.Ascending;
            }

            // 用新的排序方法对ListView排序
            this.listView1.Sort();

        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < this.listView1.Items.Count; i++)
            {
                this.listView1.Items[i].Checked = this.checkBox1.Checked;
            }
        }

        void TeamBegin()
        {
            this.Invoke(new DSetControlDisabled(SetControlDisabled));

            if (myCarTeamInfo != null)
            {
                bool team_already_begin_flag;

                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]启动车队：",
                   DateTime.Now.ToString("HH:mm:ss"),
                   string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

                OilInfo oilInfo = _user.GetTeamBeginOilInfo(myCarTeamInfo.matchuid, myCarTeamInfo.matchid, out team_already_begin_flag);
                if (!team_already_begin_flag)
                {
                    if (oilInfo != null)
                    {
                        string message = Team.teambegin(verify, oilInfo.teamuid, oilInfo.teamid);
                        message = message ?? "你的车队已成功启动！";

                        Console.WriteLine(message);
                        this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]{2}",
                            DateTime.Now.ToString("HH:mm:ss"),
                            string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
                            message)));

                        MessageBox.Show(message);
                    }
                }
                else
                {
                    this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]你的车队今天已经启动！",
                       DateTime.Now.ToString("HH:mm:ss"),
                       string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

                    MessageBox.Show("你的车队今天已经启动！");
                }

                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]完成启动车队！\n",
                   DateTime.Now.ToString("HH:mm:ss"),
                   string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

            }

            this.Invoke(new DSetControlDisabled(RestoreControlEnabled));
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(TeamBegin));
            t.Start();
            lstThread.Add(t);
        }

        delegate void DFillListView(IList<TeamInfo> teamInfos);

        void FillListView(IList<TeamInfo> teamInfos)
        {
            ListViewItem[] listViewItems = new ListViewItem[teamInfos.Count];

            this.listView1.Items.Clear();

            for (int i = 0; i < teamInfos.Count; i++)
            {
                TeamInfo teamInfo = teamInfos[i];

                listViewItems[i] = new ListViewItem(
                    new string[] { 
                            teamInfo.info, 
                            teamInfo.canoil ? "√" : "×",
                            teamInfo.teamday.ToString()});

                listViewItems[i].Tag = teamInfo;

            }
            this.listView1.Items.AddRange(listViewItems);
        }

        delegate void DSetControlDisabled();
        void SetControlDisabled()
        {
            this.button1.Enabled = false;
            this.button3.Enabled = false;
            this.button4.Enabled = false;
            this.button5.Enabled = false;
            this.listView1.Enabled = false;
            this.button2.Enabled = false;
            this.button6.Enabled = false;
            this.button7.Enabled = false;
            this.button8.Enabled = false;
            this.button9.Enabled = false;
            this.button10.Enabled = false;
            this.button11.Enabled = false;
            this.button12.Enabled = false;
        }

        delegate void DRestoreControlEnabled();
        void RestoreControlEnabled()
        {
            this.button1.Enabled = true;
            this.button3.Enabled = true;
            this.button4.Enabled = true;
            this.button5.Enabled = true;
            this.listView1.Enabled = true;
            this.button2.Enabled = true;
            this.button6.Enabled = true;
            this.button7.Enabled = true;
            this.button8.Enabled = true;
            this.button9.Enabled = true;
            if (myCarTeamInfo != null)
            {
                this.label1.Text = myCarTeamInfo.CarTeamName;
                if (myCarTeamInfo.matchid == 0 || myCarTeamInfo.matchuid == 0)
                {
                    this.button6.Enabled = false;
                    this.button1.Enabled = false;
                    this.button4.Enabled = false;
                    this.button5.Enabled = false;
                    this.button10.Enabled = true;
                    this.button11.Enabled = true;
                    this.button12.Enabled = true;
                }
                else
                {
                    this.button6.Enabled = false;
                    this.button7.Enabled = true;
                    this.button10.Enabled = false;
                    this.button11.Enabled = false;
                    this.button12.Enabled = false;
                }
                if (myCarTeamInfo.UnionFlag)
                    button7.Text = "解除联合";
                else
                    button7.Text = "解散车队";
            }
            else
            {
                this.label1.Text = "还没有组建车队！";
                this.button6.Enabled = true;
                this.button7.Enabled = false;
                this.button1.Enabled = false;
                this.button4.Enabled = false;
                this.button5.Enabled = false;
            }

        }
        delegate void DAppendText(string text);

        delegate void DFetchTeamInfos();
        void FetchTeamInfos()
        {
            this.Invoke(new DSetControlDisabled(SetControlDisabled));

             this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]开始登录系统……",
                DateTime.Now.ToString("HH:mm:ss"),
                string.Format("{0}", _accountInfo.Email))));

             if (_user.Login(_accountInfo))
             {
                 this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]登录系统成功！\n",
                     DateTime.Now.ToString("HH:mm:ss"),
                     string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

                 //_accountInfo.FriendInfos = _user.GetAllUserInfos();
                 //Account.StaticFriends(_accountInfo);

                 this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]获取拉力赛信息：",
                     DateTime.Now.ToString("HH:mm:ss"),
                     string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

                 MyTeamInfo myTeamInfo = _user.GetMyTeamInfo(ref verify);

                 myCarTeamInfo = myTeamInfo.MyCarTeamInfo;

                 IList<TeamInfo> teamInfos = myTeamInfo.TeamInfos;

                 this.Invoke(new DFillListView(FillListView), teamInfos);

                 this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]获取拉力赛信息完成！\n",
                     DateTime.Now.ToString("HH:mm:ss"),
                     string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

                 _user.Logout();

                 this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]成功退出系统！\n",
                     DateTime.Now.ToString("HH:mm:ss"),
                     string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));
             }
             this.Invoke(new DSetControlDisabled(RestoreControlEnabled));
        }

        private void MyTeam_Load(object sender, EventArgs e)
        {
            IList<SimpleUserInfo> simpleUserInfos = _accountInfo.FriendInfos;
            for (int i = 0; i < _accountInfo.FriendInfos.Count; i++)
            {
                SimpleUserInfo simpleUserInfo = _accountInfo.FriendInfos[i];
                htFriend[simpleUserInfo.uid] = simpleUserInfo;
            }
            Thread t = new Thread(new ThreadStart(FetchTeamInfos));
            t.Start();
            lstThread.Add(t);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            is_oil_flag = true;
            oil();
        }

        void oil()
        {
            IList<TeamInfo> teamInfos = new List<TeamInfo>();

            for (int i = 0; i < this.listView1.Items.Count; i++)
            {
                TeamInfo teamInfo = (TeamInfo)this.listView1.Items[i].Tag;
                if (this.listView1.Items[i].Checked)
                {
                    teamInfos.Add(teamInfo);
                }
            }
            if (teamInfos.Count == 0)
            {
                MessageBox.Show("尚未选择项！");
                return;
            }

            Thread t = new Thread(new ParameterizedThreadStart(ThreadOIL));
            t.Start(teamInfos);
            lstThread.Add(t);
 
        }

        public void Stop()
        {
            lstThread = lstThread.Where(t => t.IsAlive).ToList();

            if (lstThread.Count > 0)
            {
                this.Invoke(new DAppendText(_ownerForm.AppendText),
                    string.Format("[{0}]：正在中断当前执行线程……",
                        DateTime.Now.ToString("HH:mm:ss")));

                for (int i = 0; i < lstThread.Count; i++)
                {
                    lstThread[i].Abort();
                }

                this.Invoke(new DAppendText(_ownerForm.AppendText),
                    string.Format("[{0}]：中断当前执行线程完成！\n",
                        DateTime.Now.ToString("HH:mm:ss")));
            }
        }

        void ThreadOIL(object obj)
        {
            this.Invoke(new DSetControlDisabled(SetControlDisabled));

            this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]{2}：\n",
               DateTime.Now.ToString("HH:mm:ss"),
               string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
               (is_oil_flag ? OilType.加油 : OilType.捣鬼).ToString())));

            this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]开始登录系统……",
               DateTime.Now.ToString("HH:mm:ss"),
               string.Format("{0}", _accountInfo.Email))));

            if (_user.Login(_accountInfo))
            {
                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]登录系统成功！\n",
                    DateTime.Now.ToString("HH:mm:ss"),
                    string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

                IList<TeamInfo> teamInfos = (List<TeamInfo>)obj;
                for (int i = 0; i < teamInfos.Count; i++)
                {
                    TeamInfo teamInfo = teamInfos[i];
                    if (teamInfo.teamday != 0)
                    {
                        if (teamInfo.canoil || is_can_oil_flag)
                        {
                            IList<OilInfo> oilInfos = _user.GetUserTeamOilInfos(teamInfo.matchuid, teamInfo.matchid);

                            for (int j = 0; j < oilInfos.Count; j++)
                            {
                                OilInfo oilInfo = oilInfos[j];
                                teamInfo.CarTeamInfos[j].OilInfo = oilInfo;
                            }

                            bool is_friend = false;
                            for (int j = 0; j < teamInfo.CarTeamInfos.Count; j++)
                            {
                                is_friend = false;
                                CarTeamInfo carTeamInfo = teamInfo.CarTeamInfos[j];
                                OilInfo oilInfo = teamInfo.CarTeamInfos[j].OilInfo;

                                for (int k = 0; k < carTeamInfo.SimpleUserInfos.Count; k++)
                                {
                                    if (htFriend[carTeamInfo.SimpleUserInfos[k].uid] != null)
                                    {
                                        is_friend = true;
                                        break;
                                    }
                                }
                                if (is_friend && oilInfo != null)
                                {
                                    try
                                    {
                                        this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]{2}",
                                            DateTime.Now.ToString("HH:mm:ss"),
                                            string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
                                            Team.Oil(verify, oilInfo.teamuid, oilInfo.teamid, is_oil_flag ? OilType.加油 : OilType.捣鬼))));
                                    }
                                    catch (Exception ex)
                                    {
                                        this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]执行异常：{2}",
                                            DateTime.Now.ToString("HH:mm:ss"),
                                            string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
                                            ex.Message)));
                                    }

                                    if (j + 1 < oilInfos.Count)
                                        Thread.Sleep(_ownerForm.delayConnect * 1000);
                                }
                                else
                                {
                                    //this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]{2}",
                                    //    DateTime.Now.ToString("HH:mm:ss"),
                                    //    string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
                                    //    string.Format("{0}不是你的好友，不能给该车队加油或捣鬼。", string.Join("-", GetArray<string>.Get(carTeamInfo.SimpleUserInfos.Select(u => u.real_name).ToList()))))));
                                }
                            }
                            if (is_friend && i + 1 < teamInfos.Count)
                                Thread.Sleep(_ownerForm.delayConnect * 1000);
                        }
                        else
                        {
                            this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]{2}",
                                DateTime.Now.ToString("HH:mm:ss"),
                                string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
                                string.Format("状态显示[{0}]油已加满，不能给该车队加油或捣鬼。",
                                    teamInfo.info))));
                        }
                    }
                    else
                    {
                        this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]{2}",
                            DateTime.Now.ToString("HH:mm:ss"),
                            string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
                            "今天是比赛的第0天，还不能给车队加油或捣鬼！从明天开始，每天从00:00到车队行驶结束这段期间，你都可以给该车队加油或捣鬼。")));
                    }
                }

                _user.Logout();

                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("\n[{0}]：[{1}]成功退出系统！\n",
                    DateTime.Now.ToString("HH:mm:ss"),
                    string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

            }
            this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]{2}完成！\n",
               DateTime.Now.ToString("HH:mm:ss"),
               string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
               (is_oil_flag ? OilType.加油 : OilType.捣鬼).ToString())));

            this.Invoke(new DSetControlDisabled(RestoreControlEnabled));
        }

        private void button3_Click(object sender, EventArgs e)
        {
            is_oil_flag = false;
            oil();
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            is_can_oil_flag = this.checkBox2.Checked;
        }

        private void MyTeam_FormClosing(object sender, FormClosingEventArgs e)
        {
            Stop();
        }

        void MaJiaOil(object obj)
        {
            this.Invoke(new DSetControlDisabled(SetControlDisabled));

            this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]找马甲给我加油：\n",
               DateTime.Now.ToString("HH:mm:ss"),
               string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

            IList<AccountInfo> accountInfos = (List<AccountInfo>)obj;
            bool oil_10_flag = false;
            for (int i = 0; i < accountInfos.Count; i++)
            {
                AccountInfo accountInfo = accountInfos[i];

                User user = new User();

                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]开始登录系统……",
                   DateTime.Now.ToString("HH:mm:ss"),
                   string.Format("{0}", accountInfo.Email))));

                if (user.Login(accountInfo))
                {
                    this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]登录系统成功！\n",
                        DateTime.Now.ToString("HH:mm:ss"),
                        string.Format("{0},{1}", accountInfo.UserInfo.uid, accountInfo.UserInfo.real_name))));

                    string userverify = user.GetVerify();

                    this.Invoke(new DAppendText(_ownerForm.AppendText),
                      string.Format("[{0}]：获取VerifyCode：{1}",
                          DateTime.Now.ToString("HH:mm:ss"),
                            string.Format("{0}", userverify)));

                    IList<OilInfo> oilInfos = user.GetUserTeamOilInfos(myCarTeamInfo.matchuid, myCarTeamInfo.matchid);

                    for (int j = 0; j < oilInfos.Count; i++)
                    {
                        OilInfo oilInfo = oilInfos[j];
                        if (oilInfo.teamuid == myCarTeamInfo.matchuid)
                        {
                            string message = Team.Oil(userverify, oilInfo.teamuid, oilInfo.teamid, OilType.加油);

                            Console.WriteLine(message);

                            this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]：{2}\n",
                                DateTime.Now.ToString("HH:mm:ss"),
                                string.Format("{0},{1}", accountInfo.UserInfo.uid, accountInfo.UserInfo.real_name),
                                message)));

                            if (message == "该车队今天已经被好友加油或捣鬼10次了，你不能再进行此操作。")
                                oil_10_flag = true;
                            break;
                        }
                    }

                    _user.Logout();

                    this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]成功退出系统！\n",
                        DateTime.Now.ToString("HH:mm:ss"),
                        string.Format("{0},{1}", accountInfo.UserInfo.uid, accountInfo.UserInfo.real_name))));
                }

                if (oil_10_flag)break;

                if (i + 1 < accountInfos.Count)
                    Thread.Sleep(_ownerForm.delayConnect * 1000);
            }

            this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]找马甲给我加油完成！\n",
               DateTime.Now.ToString("HH:mm:ss"),
               string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

            this.Invoke(new DSetControlDisabled(RestoreControlEnabled));
        }

        private void button4_Click(object sender, EventArgs e)
        {
            if (myCarTeamInfo != null)
            {
                IList<AccountInfo> accountInfos = new List<AccountInfo>();

                for (int i = 0; i < _accountInfo.FriendInfos.Count; i++)
                {
                    SimpleUserInfo simpleUserInfo = _accountInfo.FriendInfos[i];
                    if (_ownerForm.htAccountInfoByUid[simpleUserInfo.uid] != null)
                    {
                        AccountInfo accountInfo = (AccountInfo)_ownerForm.htAccountInfoByUid[simpleUserInfo.uid];
                        if (accountInfo.ActiveStatus == ActiveStatus.AlreadyActive)
                            accountInfos.Add(accountInfo);
                    }
                }

                if (accountInfos.Count > 0)
                {
                    Thread t = new Thread(new ParameterizedThreadStart(MaJiaOil));
                    t.Start(accountInfos);
                    lstThread.Add(t);
                }
                else
                    MessageBox.Show("未在管理的帐号中找到您当前帐号的马甲！");
            }
            else
            {
                MessageBox.Show("还没有组建车队，不能加油！");
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(FetchTeamInfos));
            t.Start();
            lstThread.Add(t);
        }

        private void button6_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(teamfound));
            t.Start();
            lstThread.Add(t);
        }

        void teamfound()
        {
            this.Invoke(new DSetControlDisabled(SetControlDisabled));

            this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]组件车队：",
               DateTime.Now.ToString("HH:mm:ss"),
               string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

            string message = Team.teamfound(verify);

            this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]{2}",
                DateTime.Now.ToString("HH:mm:ss"),
                string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
                message)));

            MessageBox.Show(message);

            this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]组件车队完成！",
               DateTime.Now.ToString("HH:mm:ss"),
               string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

            this.Invoke(new DFetchTeamInfos(FetchTeamInfos)); 

            this.Invoke(new DSetControlDisabled(RestoreControlEnabled));
        }

        private void button7_Click(object sender, EventArgs e)
        {
            Thread t = new Thread(new ThreadStart(teamDismissOrteamBreakUni));
            t.Start();
            lstThread.Add(t);

        }

        void teamDismissOrteamBreakUni()
        {
            this.Invoke(new DSetControlDisabled(SetControlDisabled));

            if (myCarTeamInfo != null)
            {
                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]{2}：",
                   DateTime.Now.ToString("HH:mm:ss"),
                   string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
                   myCarTeamInfo.UnionFlag ? "解除联合" : "解散车队"
                   )));

                string message = myCarTeamInfo.UnionFlag ? Team.TeamBreakUni(verify, myCarTeamInfo.TeamId.Value) : Team.TeamDismiss(verify, myCarTeamInfo.TeamId.Value);

                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]{2}",
                    DateTime.Now.ToString("HH:mm:ss"),
                    string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
                    message)));

                MessageBox.Show(message);

                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]完成{2}！\n",
                   DateTime.Now.ToString("HH:mm:ss"),
                   string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
                   myCarTeamInfo.UnionFlag ? "解除联合" : "解散车队"
                   )));
            }

            this.Invoke(new DFetchTeamInfos(FetchTeamInfos)); 

            this.Invoke(new DSetControlDisabled(RestoreControlEnabled));
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (myCarTeamInfo != null)
            {
                FriendsManage friendsManage = new FriendsManage(_ownerForm,_accountInfo);
                friendsManage.Send_Msg_Str = string.Format("请帮我的拉力赛加油，地址：<a href='{0}'>{0}</a>",
                    Team.GetOilLink(myCarTeamInfo.matchuid, myCarTeamInfo.matchid));
                friendsManage.ShowDialog();
            }
            else
            {
                MessageBox.Show("还没有组建车队！");
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            IList<TeamInfo> teamInfos = new List<TeamInfo>();

            for (int i = 0; i < this.listView1.Items.Count; i++)
            {
                TeamInfo teamInfo = (TeamInfo)this.listView1.Items[i].Tag;
                if (this.listView1.Items[i].Checked)
                {
                    teamInfos.Add(teamInfo);
                }
            }
            if (teamInfos.Count == 0)
            {
                MessageBox.Show("尚未选择项！");
                return;
            }

            Thread t = new Thread(new ParameterizedThreadStart(StatisticsTeamJourney));
            t.Start(teamInfos);
            lstThread.Add(t);
        }

        void StatisticsTeamJourney(object obj)
        {
            this.Invoke(new DSetControlDisabled(SetControlDisabled));

            this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]统计车队行程：\n",
               DateTime.Now.ToString("HH:mm:ss"),
               string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

            this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]开始登录系统……",
               DateTime.Now.ToString("HH:mm:ss"),
               string.Format("{0}", _accountInfo.Email))));

            StringBuilder sbStatisticsParkMoney = new StringBuilder();
            sbStatisticsParkMoney.AppendLine("车队\t是否好友车队\t比赛天数\t行驶状态\t行程（km）\t赛道总长（km）\t剩余路程（km）");

            if (_user.Login(_accountInfo))
            {
                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]登录系统成功！\n",
                    DateTime.Now.ToString("HH:mm:ss"),
                    string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

                IList<TeamInfo> teamInfos = (List<TeamInfo>)obj;

                for (int i = 0; i < teamInfos.Count; i++)
                {
                    TeamInfo teamInfo = teamInfos[i];
                    if (teamInfo.teamday != 0)
                    {
                        JourneyInfo journeyInfo = _user.GetJourneyInfo(teamInfo.matchuid, teamInfo.matchid);
                        IList<CarTeamJourneyInfo> carTeamJourneyInfos = journeyInfo.CarTeamJourneyInfos;


                        bool is_friend = false;
                        for (int j = 0; j < teamInfo.CarTeamInfos.Count; j++)
                        {
                            is_friend = false;
                            CarTeamInfo carTeamInfo = teamInfo.CarTeamInfos[j];

                            for (int k = 0; k < carTeamInfo.SimpleUserInfos.Count; k++)
                            {
                                if (htFriend[carTeamInfo.SimpleUserInfos[k].uid] != null)
                                {
                                    is_friend = true;
                                    break;
                                }
                            }

                            CarTeamJourneyInfo carTeamJourney = null;
                            for (int k = 0; k < carTeamJourneyInfos.Count; k++)
                            {
                                if (carTeamInfo.SimpleUserInfos.Where(u => u.real_name.Contains(carTeamJourneyInfos[k].CarTeamName)).Count() > 0)
                                {
                                    carTeamJourney = carTeamJourneyInfos[k];
                                    break;
                                }
                            }
                            string carTeamName = string.Format("{0}的{1}", string.Join("-", GetArray<string>.Get(carTeamInfo.SimpleUserInfos.Select(u => u.real_name).ToList())), carTeamInfo.CarTeamName);

                            if (carTeamJourney != null)
                            {
                                sbStatisticsParkMoney.AppendLine(string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}",
                                    carTeamName,
                                    is_friend ? "√" : "×",
                                    teamInfo.teamday.ToString(),
                                    carTeamJourney.MatchStatus,
                                    carTeamJourney.Journey.ToString(),
                                    journeyInfo.TotalJourney.ToString(),
                                    (journeyInfo.TotalJourney - carTeamJourney.Journey).ToString()));

                                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]：{2}！",
                                    DateTime.Now.ToString("HH:mm:ss"),
                                    string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
                                    string.Format("{0}已行驶{1}天，路程{2}km，剩余路程{3}km，当前：{4}",
                                    carTeamName,
                                    teamInfo.teamday.ToString(),
                                    carTeamJourney.Journey.ToString(),
                                    (journeyInfo.TotalJourney - carTeamJourney.Journey).ToString(),
                                    carTeamJourney.MatchStatus))));
                            }
                            else
                            {
                                sbStatisticsParkMoney.AppendLine(string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}",
                                    carTeamName,
                                    is_friend ? "√" : "×",
                                    teamInfo.teamday.ToString(),
                                    "未开始",
                                    "0",
                                    journeyInfo.TotalJourney.ToString(),
                                    journeyInfo.TotalJourney.ToString()));

                                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]：{2}！",
                                    DateTime.Now.ToString("HH:mm:ss"),
                                    string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
                                    string.Format("{0}已行驶{1}天，路程{2}km，剩余路程{3}km，当前：{4}",
                                    carTeamName,
                                    teamInfo.teamday.ToString(),
                                    "0",
                                    (journeyInfo.TotalJourney).ToString(),
                                    "未开始"))));

                            }
                        }
                    }
                    else
                    {
                        bool is_friend = false;
                        for (int j = 0; j < teamInfo.CarTeamInfos.Count; j++)
                        {
                            is_friend = false;
                            CarTeamInfo carTeamInfo = teamInfo.CarTeamInfos[j];

                            for (int k = 0; k < carTeamInfo.SimpleUserInfos.Count; k++)
                            {
                                if (htFriend[carTeamInfo.SimpleUserInfos[k].uid] != null)
                                {
                                    is_friend = true;
                                    break;
                                }
                            }
                            string carTeamName = string.Format("{0}的{1}", string.Join("-", GetArray<string>.Get(carTeamInfo.SimpleUserInfos.Select(u => u.real_name).ToList())), carTeamInfo.CarTeamName);

                            sbStatisticsParkMoney.AppendLine(string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}",
                                carTeamName,
                                is_friend ? "√" : "×",
                                "0",
                                "未开始",
                                "0",
                                "未统计",
                                "未统计"));

                            this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]：{2}！",
                                DateTime.Now.ToString("HH:mm:ss"),
                                string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
                                string.Format("{0}：比赛的第0天不进行统计！",carTeamName))));
                        }
                        //this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]{2}",
                        //    DateTime.Now.ToString("HH:mm:ss"),
                        //    string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
                        //    "今天是比赛的第0天，还不能给车队加油或捣鬼！从明天开始，每天从00:00到车队行驶结束这段期间，你都可以给该车队加油或捣鬼。")));
                    }
                    if (i + 1 < teamInfos.Count)
                        Thread.Sleep(_ownerForm.delayConnect * 1000);
                }

                _user.Logout();

                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("\n[{0}]：[{1}]成功退出系统！\n",
                    DateTime.Now.ToString("HH:mm:ss"),
                    string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

            }
            string statisticsTeamJourneyFile = Path.Combine(Application.StartupPath, "车队行程统计.xlt");

            using (StreamWriter sw = new StreamWriter(statisticsTeamJourneyFile, false, Encoding.Default))
            {
                sw.WriteLine(sbStatisticsParkMoney.ToString());
            }

            this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]车队行程统计完成，并生成统计报表：{2}！\n",
               DateTime.Now.ToString("HH:mm:ss"),
               string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
               statisticsTeamJourneyFile)));

            this.Invoke(new DSetControlDisabled(RestoreControlEnabled));
        }

        int LineId { get; set; }
        int MaxTeamNum { get; set; }

        private void button12_Click(object sender, EventArgs e)
        {
            MatchOrigin matchOriginFrm = new MatchOrigin();
            if (matchOriginFrm.ShowDialog() == DialogResult.OK)
            {
                LineId = matchOriginFrm.LineId;
                MaxTeamNum = matchOriginFrm.MaxTeamNum;
                Thread t = new Thread(new ThreadStart(matchOrigin));
                t.Start();
                lstThread.Add(t);
            }
            //Thread t = new Thread(new ThreadStart(matchOrigin));
            //t.Start();
            //lstThread.Add(t);
        }

        void matchOrigin()
        {
            this.Invoke(new DSetControlDisabled(SetControlDisabled));

            if (myCarTeamInfo != null && myCarTeamInfo.TeamId != null)
            {
                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]发起比赛：\n",
                   DateTime.Now.ToString("HH:mm:ss"),
                   string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

                string message = Team.MatchOrigin(verify, myCarTeamInfo.TeamId.Value, LineId, MaxTeamNum);

                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]{2}",
                    DateTime.Now.ToString("HH:mm:ss"),
                    string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name),
                    message)));


                this.Invoke(new DAppendText(_ownerForm.AppendText), (string.Format("[{0}]：[{1}]发起比赛完成！",
                   DateTime.Now.ToString("HH:mm:ss"),
                   string.Format("{0},{1}", _accountInfo.UserInfo.uid, _accountInfo.UserInfo.real_name))));

                this.Invoke(new DFetchTeamInfos(FetchTeamInfos));

                MessageBox.Show(message);
            }

            this.Invoke(new DSetControlDisabled(RestoreControlEnabled));
        }
    }
}
